<template>
  <div class="editTextBox">
    <!-- v-Clickoutside="handelClickoutSide" -->
    <div
      class="editText"
      :class="{
        'eidt-blur': !focus,
        'is-disabled': (!isMyCaeate && !isOtherDesiger) || !canEdit,
        unOpen: !focus,
      }"
    >
      <div
        class="open_closeEditIcon"
        v-if="focus && showUnopenBtn"
        @click="handleOpenClose"
      >
        <img :src="require('@/assets/images/down.png')" title="收起" />
      </div>
      <div class="unopenContent" v-if="!focus" @click="handelFocus">
        <div class="typeIconBox" v-if="showOtherTool">
          <img
            :src="require('@/assets/images/answer.png')"
            class="uhoverIcon"
          />
          <img
            :src="require('@/assets/images/answerHover.png')"
            class="hoverIcon"
          />
        </div>
        <div v-else class="weightInTaskBox" style="margin-left: 0">
          <span
            v-html="gitem[objKeyName] || '内容为空'"
            style="max-width: 90%"
          ></span>
        </div>
        <div class="weightInTaskBox" v-if="showOtherTool">
          <span v-html="gitem[objKeyName] || '内容为空'"></span>
          <span
            ><strong class="spanTitle">类型：</strong>{{ gitem.operType }}</span
          >
          <span
            ><strong class="spanTitle">权重：</strong
            >{{ gitem.weightInTask ? gitem.weightInTask : 1 }}</span
          >
        </div>
        <div class="openIconbox">
          <img
            :src="require('@/assets/images/down.png')"
            @click.stop="handelFocus"
            title="展开"
          />
        </div>
      </div>
      <div class="toolBar" v-show="focus && (isMyCaeate || isOtherDesiger) && canEdit">
        <div class="richTextTool toolbar" :id="`${'toolBar' + editId}`"></div>
        <!-- :id="'toolBar' + 'taskDesc-' + currTaskIndex" -->
        <!-- <div v-if="!isMyCaeate" style="align-items: center; display: flex">工具栏</div> -->
        <div class="otherTool" v-if="showOtherTool && (isMyCaeate || isOtherDesiger) && canEdit">
          <div class="weightBox" v-if="gitem.operType == '上传' || gitem.operType == '展示' || gitem.operType == '归档'">
            <el-popover
              placement="bottom"
              width="400"
              trigger="click">
              <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                <el-form-item label="上传数量" prop="limit">
                   <el-input-number v-model="ruleForm.limit" controls-position="right" @change="handleChangeLimit" size="small" placeholder="数量为0表示不限制" :min="0" :max="10"></el-input-number>
                   <span>数量为0表示不限制</span>
                </el-form-item>
                <el-form-item label="文件类型" prop="checkList">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="ruleForm.checkList" @change="handleCheckedChange">
                    <el-checkbox v-for="item in acceptType" :key="item" :label="item" ></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
              <el-button size="mini" slot="reference">文件上传限制</el-button>
            </el-popover>
            <!-- <el-input
              type="text"
              :maxlength="3"
              :max="100"
              v-model="gitem.weightInTask"
              onkeyup="this.value=this.value.replace(/[^\d%]$/g,'');"
              placeholder="引导文权重"
              @change="getEditorData"
              :key="currGroupIndex + '-' + currTaskIndex + '-' + gitem.id"
              :disabled="(!isMyCaeate && !isOtherDesiger) || !canEdit"
            >
            </el-input> -->
          </div>
          <div class="shortAnswer">
            <el-select
              v-model="gitem.operType"
              placeholder="请选择"
              popper-class="operTypeSelect"
              :popper-append-to-body="false"
              @change="handelChangeType($event, gindex)"
              :disabled="
                (!isMyCaeate && !isOtherDesiger) ||
                !canEdit ||
                (gitem.state === '已发布' && isContinuousPublish && gitem.operType =='上传')
              "
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- 简答
                    <img :src="require('@/assets/images/shortAnswer.png')" /> -->
          </div>
          <div
            class="moveIcon"
            :class="{
              uMoveIcon: !(gitem.state === '已发布' && isContinuousPublish),
            }"
            title="拖拽"
          >
            <i class="iconfont iconyidong"></i>
          </div>
        </div>
      </div>
      <div class="edit" :class="{ uShowEdit: false }" v-show="focus">
        <!-- <div :id="`${'toolBar' + editId}`" class="toolbar"></div> -->
        <!-- <div style="padding: 5px 0; color: #ccc">中间隔离带</div> -->
        <div :id="`${'edit' + editId}`"></div>
        <input
          type="file"
          accept=".pka,.txt,.css,.html,.zip,.rar,.jpg,.jpeg,.png,.gif,.bmp,.pdf,.docx,.xls,.xlsx,.pptx,.mp3,.mp4,.mpeg,.wma,.aac,.wav,.js,.doc,.DOC,.CSS,.HTML,.ZIP,.RAR,.JPG,.JPEG,.PNG,.GIF,.BMP,.PDF,.DOCX,.XLS,.XLSX,.MP3,.MP4,.MPEG,.WMA,.AAC,.WAV"
          :id="`${'uplaodFile-' + editId}`"
          style="dispaly: none !important"
          class="uploadFileInput"
          ref="uplaodFile"
        />
        <!-- v-Clickoutside="getEditorData" -->
      </div>
    </div>
    <div class="inputName" v-if="gitem.operType == '刷题' && showEditAnswerBtn" v-show="focus">
      选择题组
    </div>
    <div class="brushTopicType" v-if="gitem.operType == '刷题' && showEditAnswerBtn" v-show="focus">
      <div
        class="startMustTips"
        title="必填"
        v-if="gitem.operType == '刷题' && !gitem.foreignID"
      >
        *
      </div>
      <div style="width: 75%">
        <span
          >题组：{{
            gitem.foreignID
              ? gitem.foreign_title
                ? gitem.foreign_title
                : "已选的题组名称为空(请重新选择题组后保存！)"
              : "未选择题组"
          }}</span
        >
        <!-- <span v-for="(item, index) in testlet" :key="index">
          {{ item.title }} {{ index + 1 == testlet.length ? '' : '、' }}
        </span> -->
        <!-- <span v-if="!gitem.foreignID">暂未选择题组</span> -->
      </div>
      <div class="btnListBox">
        <el-button
          type="text"
          class="btn"
          @click="handleShowQuestionBankIframe"
          v-if="(isMyCaeate || isOtherDesiger) && canEdit && !gitem.foreignID"
          :disabled="!(isMyCaeate || isOtherDesiger) || !canEdit"
        >
          新建
        </el-button>
        <el-button type="text" class="btn" @click="handleEditTestLet(gitem)" v-else
          :disabled="!(isMyCaeate || isOtherDesiger) || !canEdit">编辑</el-button>
        <el-button
          type="text"
          class="btn"
          @click="handelShowSelectTestlet"
          v-if="(isMyCaeate || isOtherDesiger) && canEdit"
          :disabled="!(isMyCaeate || isOtherDesiger) || !canEdit"
        >
          {{ !gitem.foreignID ? "选择" : "重选" }}
        </el-button>
        <el-button
          type="text"
          class="btn"
          v-if="(isMyCaeate || isOtherDesiger) && canEdit && gitem.foreignID"
          @click="handleTestQuestionGroup"
          :disabled="!(isMyCaeate || isOtherDesiger) || !canEdit"
        >
          试做
        </el-button>
        <el-button
          type="text"
          class="btn"
          v-if="(isMyCaeate || isOtherDesiger) && canEdit && gitem.foreignID"
          @click="handleClearForeignID"
          :disabled="!(isMyCaeate || isOtherDesiger) || !canEdit"
        >
          清空
        </el-button>
      </div>
    </div>
    <!-- 创建题组 -->
    <brushQuestions
      :title="`${isCreate? '新建' : '修改'}题组`"
      :iframeShow="iframeShow"
      :iframeRouter="iframeRouter"
      :creatTestlet="true"
      @createdTestlet="saveTestlet"
      @handleIframeClose="handleIframeClose"
      key="creativeQuestionGroup"
      :designCourseInfo="designCourseInfo"
    />
    <!-- 试做题组 -->
    <brushQuestions
      :title="`试做题组`"
      :iframeShow="showBrush"
      :iframeRouter="brushIframeRouter"
      :testQuestionGroup="true"
      :foreignID="gitem.foreignID"
      @handleIframeClose="handleTestTopicIframeClose"
      key="brush"
    />
    <!-- 选择题组 -->
    <brushQuestions
      :title="`选择题组`"
      v-if="(isMyCaeate || isOtherDesiger) && canEdit && gitem.operType == '刷题'"
      :iframeShow="showSelectTestlet"
      :iframeRouter="selectIframeRoute"
      :selectQuestionGroup="true"
      :foreignID="gitem.foreignID"
      @handleIframeClose="handelCloseSelectTestlet"
      @saveTestlet="saveTestlet"
      key="save"
    />
    <!-- <selectTestlet
      v-if="(isMyCaeate || isOtherDesiger) && canEdit && gitem.operType == '刷题'"
      :showSelectTestlet="showSelectTestlet"
      :foreignID="gitem.foreignID"
      @close="handelCloseSelectTestlet"
      @saveTestlet="saveTestlet"
    /> -->
    <!-- <questionBankComponent
      @handleIframeClose="handleIframeClose"
      :iframeShow="iframeShow"
      :iframeRouter="iframeRouter"
      @createdTestlet="saveTestlet"
    /> -->
    <editInputDialog
      v-if="showEditAnswerBtn"
      :showEditInput="showEditInput"
      @handleChangeEditInput="handleChangeEditInput"
      @handleEditInputClose="handleEditInputClose"
      :gitem="gitem"
      :gindex="gindex"
      :currGroupIndex="currGroupIndex"
      :currTaskIndex="currTaskIndex"
      :isMyCaeate="isMyCaeate"
      :isOtherDesiger="isOtherDesiger"
      :canEdit="canEdit"
      :isContinuousPublish="isContinuousPublish"
    />
  </div>
</template>

<script type="text/javascript">
import wangEditor from "wangeditor";
import { d_uploadmultifiles } from "@/request/upload";
// const selectTestlet = () =>
//   import("../selectTestletComponent/newSelectTestlet");
import { mapState } from "vuex";
import { encryptionToString } from "@/util/qetag";
// const questionBankComponent = () =>
//   import("../questionBankComponent/questionBankComponent");
import {
  location,
  location_QuestionBank,
  VideoUpload,
  guid,
} from "@/util/tool";

import { loadAllVideo } from "@/util/loadVideo";
import { notUploadFileType } from "@/util/uploadConfig";
const editInputDialog = () =>
  import("@/views/creativeCourses/creative/component/editInputDialog");
const brushQuestions = () => import("@/components/questionBankIframeDialog/index");

// import E from 'wangeditor'
// import { updateExplain, getExplain } from '@/api/instructions'

export default {
  name: "WriteArticle",
  components: {
    // selectTestlet,
    // questionBankComponent,
    editInputDialog,
    brushQuestions,
  },
  data() {
    return {
      editor: null,
      editorData: "",
      options: [
        {
          value: "查阅",
          label: "查阅",
        },
        // {
        //   value: '播放',
        //   label: '播放',
        // },
        {
          value: "上传",
          label: "上传",
        },
        {
          value: "游戏",
          label: "游戏",
        },
        {
          value: "简答",
          label: "简答",
        },
        {
          value: "刷题",
          label: "刷题",
        },
        {
          value: "展示",
          label: "展示",
        },
        {
          value: "归档",
          label: "归档",
        }
        // {
        //   value: '下载',
        //   label: '下载',
        // },
        // {
        //   value: '无互动',
        //   label: '无互动',
        // },
      ],
      acceptType: [
        '.txt',
        '.css',
        '.html',
        '.zip',
        '.rar',
        '.jpg',
        '.jpeg',
        '.png',
        '.gif',
        '.pdf',
        '.doc',
        '.docx',
        '.xls',
        '.xlsx',
        '.pptx',
        '.mp3',
        '.mp4',
        '.js',
      ],
      focus: false, // 获取焦点
      showSelectTestlet: false, // 显示刷题选择弹出框
      selectIframeRoute: "", // 选择题组路由
      // testlet: [],
      iframeShow: false, // 显示题库iframe
      iframeRouter: "", // iframe打开的页面
      isRendering: false, // 是否已经初始化内容
      showEditInput: false, // 控制显示编辑评阅标准、参考答案弹出框
      showBrush: false, // 显示刷题组件
      brushIframeRouter: "", // 刷题地址
      isCreate: true, // 创建题组或编辑题组
      ruleForm: {
        limit: 0, // 数量
        checkList: [
          '.txt',
          '.css',
          '.html',
          '.zip',
          '.rar',
          '.jpg',
          '.jpeg',
          '.png',
          '.gif',
          '.pdf',
          '.doc',
          '.docx',
          '.xls',
          '.xlsx',
          '.pptx',
          '.mp3',
          '.mp4',
          '.js',
        ], // 上传类型选择的文件类型
      },
      checkAll: true,
      isIndeterminate: true,
      rules: {
        limit: [
          { required: true, message: '请输入文件上传数量', trigger: 'blur' },
        ],
        checkList: [
          { required: true, message: '请选择可上传文件类型', trigger: 'change' }
        ],
      }
    };
  },
  props: {
    placeholder: String,
    editId: String,
    gindex: Number, // 引导文的索引值
    gitem: {
      type: Object,
      default: function () {
        return {
          qgid: null,
          title: "",
        };
      },
    },
    maxlength: Number,
    showWordLimit: Boolean,
    notUpload: Boolean,
    newKey: String,
    currGroupIndex: Number,
    currTaskIndex: Number,
    showOtherTool: Boolean, // 显示其他设置
    showUnopenBtn: Boolean, // 收起按钮
    isMyCaeate: Boolean, // 是否自己设计的
    isOtherDesiger: Boolean, // 是否是自己设计的
    canEdit: Boolean, // 当前课程状态可否编辑
    // 是否持续发布
    isContinuousPublish: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
    objKeyName: String, // 键名
    // 显示打开编辑评阅标准、参考答案的按钮
    showEditAnswerBtn: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
    courseDetailData: Object
  },
  watch: {
    isMyCaeate(n, o) {
      if (!n) {
        this.editor.$textElem.attr("contenteditable", false);
      }
    },
    canEdit(n, o) {
      if (!n) {
        this.editor.$textElem.attr("contenteditable", false);
      }
    },
    focus(n, o) {
      this.loadAllVideo();
      this.handleEmitFoucs(n);
    },
    showEditAnswerBtn(n) {
      this.showBrush = n;
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    checkTaskState() {
      return (
        this.$parent.$parent.$parent.$parent.courseDetailData.content[
          this.currGroupIndex
        ].tasks[this.currTaskIndex].state === "已发布"
      );
    },
    designCourseInfo() {
      return {
        courseID: Number(this.$route.params?.id),
        courseName: this.courseDetailData?.name,
        authorName: this.userInfo?.realName || this.userInfo?.email || this.userInfo?.regName
      }
    }
  },
  created() {
    if (this.focus) {
      this.handleEmitFoucs(this.focus);
    }
  },
  mounted() {
    const _that = this;
    const antdMessage = this.$antdMessage;

    this.editor = null;
    this.editor = new wangEditor(
      `${"#toolBar" + this.editId}`,
      `${"#edit" + this.editId}`
    );

    // // 配置 onchange 回调函数，将数据同步到 vue 中
    // editor.config.onchange = (newHtml) => {
    //   this.editorData = newHtml
    // }

    /**
     * @params
     *  uploadImgServer 配置api接口
     *  withCredentials 跨域携带cookie
     *  uploadImgParams 请求头参数
     *  customUploadImg 回调函数
     */

    // 使用 base64 保存图片
    // this.editor.config.uploadImgShowBase64 = true
    this.editor.config.uploadImgServer = "/d_api/utils/uploadfiles";
    this.editor.config.withCredentials = true;
    this.editor.config.uploadImgParams = {
      Accept: "application/json",
    };
    this.editor.config.customUploadImg = async function (
      resultFiles,
      insertImgFn
    ) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      let nFormData = new FormData();
      let hashArray = [];
      for (let item of resultFiles) {
        // 文件名
        let fileName = item.name;
        // 过滤英文分号
        if (item.name.indexOf(";") !== -1) {
          fileName = item.name.replace(/;/g, "");
        }

        let hash = await encryptionToString({ raw: item });
        if (hash === "Fto5o-5ea0sNMlW_75VgGJCv2AcJ") {
          this.$antdMessage.error({
            content: "文件读取错误！",
          });
          return;
        }
        if (hash) hashArray.push(hash);

        nFormData.append("file", item, fileName);
      }
      nFormData.append(
        "courseInfo",
        JSON.stringify({
          userID: _that.userInfo.userID,
          // 文件内容hash
          FileHashArray: JSON.stringify(hashArray),
        })
      );

      d_uploadmultifiles(nFormData)
        .then((res) => {
          if (!res.data.filePaths.length) {
            _that.$antdMessage.error({
              content: "上传失败",
            });
            return;
          }
          if (res.errno === 0) {
            // let fileUrl = res.split("上传成功！文件地址分别为：")[1];
            let fileUrl = res.data.filePaths;
            if (fileUrl) {
              // 上传图片，返回结果，将图片插入到编辑器中
              fileUrl.forEach((item) => {
                item = item.split(item.substring(item.lastIndexOf("&")))[0];
                insertImgFn(location(window) + item);
              });
              _that.$nextTick(() => {
                _that.loadAllVideo();
              });
            }
          }
        })
        .catch((err) => console.log(err));
    };

    /**
     * @params
     *  uploadVideoServer 配置api接口
     *  withVideoCredentials 跨域携带cookie
     *  uploadVideoHeaders 请求头参数
     *  uploadVideoHooks 回调函数
     */
    this.editor.config.uploadVideoServer = "/d_api/utils/uploadfiles";
    this.editor.config.withVideoCredentials = true;
    this.editor.config.uploadVideoHeaders = {
      Accept: "application/json",
    };
    this.editor.config.customUploadVideo = async function (
      resultFiles,
      insertVideoFn
    ) {
      let videoUploadForm = new FormData();
      for (let vi = 0; vi < resultFiles.length; vi++) {
        // 文件名
        let fileName = resultFiles[vi].name;
        // 过滤英文分号
        if (resultFiles[vi].name.indexOf(";") !== -1) {
          fileName = resultFiles[vi].name.replace(/;/g, "；");
        }
        // 添加文件对象到formData
        videoUploadForm.append("file", resultFiles[vi], fileName);
      }
      // 上传视频
      VideoUpload(videoUploadForm).then((res) => {
        if (res) {
          if (res.code == 200) {
            let currGuid = guid();
            _that.editor.txt.append(
              `<p><video ref="video "id="${currGuid}" :src="${res.data.hdAddress}" autoplay="true" controls="true" ishowprocessview="true" x5-playsinline="" playsinline=""webkit-playsinline="" x5-video-player-type="h5" x5-video-player-fullscreen="false" direction="0" show-play-btn="true" object-fit="cover"></video></p><p data-we-empty-p />`
            );
            _that.editor.txt.append(`<p><br></p>`);
            _that.$nextTick(() => {
              // _that.setUrlToVideo(res.data.hdAddress,currGuid);
              _that.loadAllVideo();
            });
          } else {
            _that.$antdMessage.error({
              content: res.message || res.msg || "视频上传失败！",
            });
          }
        } else {
          _that.$antdMessage.error({
            content: "视频上传失败！",
          });
        }
      });
    };

    // onchange回调时间 无效
    // this.editor.config.onchangeTimeout = 500
    // 内容修改回调
    this.editor.config.onchange = function (newHtml) {
      _that.getEditorData();
    };

    this.editor.config.menus = 
      [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "underline", // 下划线
        "foreColor", // 文字颜色
        "justify", // 对齐方式
        "image", // 插入图片
        "video", // 插入视频
        "link", // 链接
        "undo", // 撤消
        "redo", // 重复
      ];
    // 配置菜单栏，如果notUpload为true则不显示上传图片和视频功能
    if (this.notUpload) {
      this.editor.config.menus = this.editor.config.menus
        .filter((item) => item !== "uploadImage")
        .filter((item) => item !== "uploadVideo");
    }
    
    const { $, BtnMenu, DropListMenu, PanelMenu, DropList, Panel, Tooltip } =
      wangEditor;

    // 第一，菜单 class ，Button 菜单继承 BtnMenu class
    class uploadFileMenu extends BtnMenu {
      constructor(editor) {
        // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
        // 如果notUpload为true则不显示该按钮
        const $elem = wangEditor.$(_that.notUpload ? '' :
          `<div class="w-e-menu" data-title="上传附件">
                <i class="iconfont iconfile" style="color:#999;"></i>
            </div>`
        );
        super($elem, editor);
      }
      // 菜单点击事件
      clickHandler() {
        // 可参考【常用 API】文档，来操作编辑器
        let fileUplaod = document.getElementById(
          `${"uplaodFile-" + _that.editId}`
        );
        let outerHTML = fileUplaod.outerHTML;
        fileUplaod.click();
        fileUplaod.addEventListener("change", async function () {
          var t_files = this.files;
          let file = t_files[this.files.length - 1];
          // 修复打开多次上传文件后 只上传最后一次 出现多个文件
          fileUplaod.value = "";
          const uLoadFileType = notUploadFileType;
          if (!file) return; // 避免多次触发onchange
          if (
            uLoadFileType.indexOf(file.type) !== -1 ||
            uLoadFileType.indexOf(
              file.name.substring(file.name.lastIndexOf("."))
            ) !== -1
          ) {
            antdMessage.error({
              content: "此类型文件无法上传！",
            });
            return;
          }
          if (file.size > 1000000000) {
            antdMessage.error({
              content: "文件大小不能超过1Gb",
            });
            return;
          }
          let nFormData = new FormData();
          let hashArray = [];

          // 文件名
          let fileName = file.name;

          let hash = await encryptionToString({ raw: file });
          if (hash === "Fto5o-5ea0sNMlW_75VgGJCv2AcJ") {
            antdMessage.error({
              content: "文件读取错误！",
            });
            return;
          }
          if (hash) hashArray.push(hash);

          // 过滤英文分号
          if (file.name.indexOf(";") !== -1) {
            fileName = file.name.replace(/;/g, "");
          }
          nFormData.append("file", file, fileName);
          nFormData.append(
            "courseInfo",
            JSON.stringify({
              userID: _that.userInfo.userID,
              FileHashArray: JSON.stringify(hashArray),
            })
          );
          d_uploadmultifiles(nFormData)
            .then((res) => {
              if (!res.data.filePaths.length) {
                _that.$antdMessage.error({
                  content: file.name + "上传失败",
                });
                return;
              }
              if (res.errno === 0) {
                // let fileUrl = res.split("上传成功！文件地址分别为：")[1];
                let fileUrl = res.data.filePaths[0];
                if (fileUrl) {
                  const fileName = fileUrl.substring(
                    fileUrl.lastIndexOf("&") + 1
                  );
                  fileUrl = fileUrl.split(
                    fileUrl.substring(fileUrl.lastIndexOf("&"))
                  )[0];
                  //  上传文件，返回结果，将文件地址插入到编辑器中
                  // 在光标当前位置插入
                  _that.editor.cmd.do(
                    "insertHTML",
                    `<p><a href="${
                      location(window) + fileUrl
                    }" style="text-decoration: underline;">${fileName}</a></p>`
                  );
                  _that.$nextTick(() => {
                    _that.loadAllVideo();
                  });
                }
              }
            })
            .catch((err) => console.log(err));
          _that.$nextTick(() => {
            fileUplaod.value = "";
            fileUplaod.outerHTML = outerHTML;
          });
          // fileUplaod.value = "";
        });
      }
      // 菜单是否被激活（如果不需要，这个函数可以空着）
      // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
      // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
      tryChangeActive() {
        // 激活菜单
        // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
        // 2. this.this.isActive === true
        this.active();

        // // 取消激活菜单
        // // 1. 菜单 DOM 节点会删掉 .w-e-active
        // // 2. this.this.isActive === false
        // this.unActive()
      }
    }

    class setGuidelineAnswer extends BtnMenu {
      constructor(editor) {
        // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
        const $elem = wangEditor.$(
          `<div class="w-e-menu" data-title="评阅标准、参考答案">
                  <i class="iconfont iconcankaodaan" style="color:#999;"></i>
              </div>`
        );
        super($elem, editor);
      }
      clickHandler() {
        _that.handleShowEditInputDialog();
      }
      tryChangeActive() {
        // 激活菜单
        // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
        if (_that.showEditAnswerBtn && this.objKeyName !== "description") {
          this.active();
        } else {
          this.unActive();
        }
      }
    }

    // 菜单 key ，各个菜单不能重复
    const uFileMenu = "uploadFileMenu";
    const sGLAKey = "setGuidelineAnswer";

    // 自动获取焦点
    this.editor.config.focus = true;

    // 隐藏tooltips菜单
    this.editor.config.showMenuTooltips = true;

    // 当前状态是否能编辑
    if ((!this.isMyCaeate && !this.isOtherDesiger) || !this.canEdit) {
      this.editor.config.menus = [];
    } else {
      // 注册菜单
      // wangEditor.registerMenu(uFileMenu, uploadFileMenu); // 全局注册
      // 局部注册菜单
      this.editor.menus.extend(uFileMenu, uploadFileMenu);
      this.editor.config.menus.push(uFileMenu);
      const keyNameIsDescription = this.objKeyName === "description";
      if (this.showEditAnswerBtn && keyNameIsDescription) {
        // wangEditor.registerMenu(sGLAKey, setGuidelineAnswer); // 全局注册
        // 局部注册菜单
        this.editor.menus.extend(sGLAKey, setGuidelineAnswer);
        this.editor.config.menus.push(sGLAKey);
      }
    }

    // 失去焦点
    // this.editor.config.onblur = (newHtml) => {
    //   this.focus = false;
    // };
    // 获得焦点
    this.editor.config.onfocus = (newHtml) => {
      this.focus = true;
    };

    this.editor.config.placeholder = this.placeholder;

    // 创建编辑器
    this.editor.create();

    // 获取使用说明
    // getExplain({ id: 2 }).then(res => {
    //   if (res.code == 0) {
    //     editor.$textElem.elems[0].innerHTML = res.data.content
    //   }
    // })
    if (this.gitem[this.objKeyName]?.length) {
      // this.editor.txt.html(this.gitem[this.objKeyName])
      // this.$nextTick(() => {
      //   document
      //     .getElementById(`${"edit" + this.editId}`)
      //     .getElementsByClassName("w-e-text-container")[0]
      //     .getElementsByClassName("w-e-text")[0].innerHTML =
      //     this.gitem[this.objKeyName];
      // });
      this.editor.$textElem.elems[0].innerHTML = this.gitem[this.objKeyName];
      // 初始化内容后才能触发submit回调
      setTimeout(() => {
        this.isRendering = true;
      }, 200);
    } else {
      this.isRendering = true;
    }

    // 禁用编辑器
    if ((!this.isMyCaeate && !this.isOtherDesiger) || !this.canEdit) {
      this.editor.$textElem.attr("contenteditable", false);
    }

    this.gitem.limit && (this.ruleForm.limit = this.gitem.limit)
    this.gitem.accept && (this.ruleForm.checkList = this.gitem.accept.split(','))

    // 加载所有视频
    this.$nextTick(() => {
      this.loadAllVideo();
    });
  },
  methods: {
    getEditorData() {
      // 如果还没初始化 或 编辑器不存在 则 返回
      if (!this.isRendering || !this.editor) return;
      // 通过代码获取编辑器内容
      let data = this.editor.txt.html();
      // 只移除最前和最后部分的HTML标签，不移除中间的HTML标签
      let pureText = data.replace(/^(<[^>]+>)+|(<[^>]+>)+$/g, '');
      let maxlength = this.maxlength || 5000;
      if (pureText.length > maxlength) {
          // 截断文本
          var truncatedText = pureText.substring(0, maxlength);
          this.editor.txt.html(truncatedText); // 设置编辑器内容为截断后的文本
          this.$antdMessage.warning({
              content: "已超出最大字数（含文件）限制，内容已被截断！",
          });
      }
      // 修改使用说明
      // updateExplain({ content: data, id: 2 }).then(res => {
      //   if (res.code == 0) {
      //     this.$message.success('修改成功')
      //     // this.$router.reload()
      //   }
      // })
      this.$emit("submit", {
        data: data,
        id: this.editId,
        gindex: this.gindex,
      });
    },
    // 点击上传文档
    hadnelUploadFile() {
      let fileUplaod = document.getElementById(
        `${"uplaodFile-" + this.editId}`
      );
      fileUplaod.click();
    },
    // 输入框数去焦点 用户体验一般
    handelClickoutSide() {
      this.focus = false;
    },
    // 打开选择题组
    handelShowSelectTestlet() {
      this.showSelectTestlet = true;
      this.selectIframeRoute = `${location_QuestionBank(window)}/testlet/select`
      //this.selectIframeRoute = '/qb/testlet/select'
    },
    // 关闭选择题组
    handelCloseSelectTestlet() {
      this.showSelectTestlet = false;
      this.selectIframeRoute = ''
    },
    // 保存题组
    saveTestlet(item) {
      this.gitem.foreignID = item.gid;
      this.gitem.foreign_title = item.title;
      this.gitem.foreign_type = item.groupType;
      // this.gitem.questionGroupDetail = {
      //   gid: item.gid,
      //   title: item.title,
      // }
      this.getEditorData();
      this.handelCloseSelectTestlet();
    },
    // 展开
    handelFocus() {
      this.focus = true;
    },
    // 点击按钮展开收缩引导文
    handleOpenClose() {
      this.focus = !this.focus;
    },
    // 选择引导文类型
    handelChangeType(val, gindex) {
      this.gitem.foreignID = 0;
      this.gitem.foreign_title = "";
      if (val == '上传' || val == '展示' || val == '归档') {
        this.gitem.accept = this.acceptType.join(',')
        this.gitem.limit = this.ruleForm.limit
      }
      // debugger
      this.$parent.$parent.$parent.handelChange("guidelines");
      // this.operType = val
    },
    // 打开题库iframe Dialog
    handleShowQuestionBankIframe() {
      this.iframeRouter = `${location_QuestionBank(window)}/testlet/add`;
      // this.iframeRouter = "http://localhost:3000/qb/testlet/add";
      this.iframeShow = true;
      this.isCreate = true
    },
    handleEditTestLet(item) {
      this.iframeRouter = `${location_QuestionBank(window)}/testlet/${
        item.foreignID
      }`;
      // this.iframeRouter = `http://localhost:3000/qb/testlet/${item.foreignID}`;
      this.iframeShow = true;
      this.isCreate = false
    },
    // 关闭iframe
    handleIframeClose() {
      // this.fetchQuestionGroupList();
      this.iframeShow = false;
    },
    // 如果当前引导文已打开 将索引传给父组件
    handleEmitFoucs(focus) {
      this.$emit("watchFocus", this.gindex, focus);
    },
    // 加载所有视频
    loadAllVideo() {
      return loadAllVideo(this, true);
    },
    // 编辑评阅标准、参考答案
    handleShowEditInputDialog() {
      this.showEditInput = true;
    },
    // 关闭Dialog
    handleEditInputClose() {
      this.showEditInput = false;
    },
    // 更新评阅标准、参考答案的数据
    handleChangeEditInput(val, keyName) {
      this.gitem[keyName] = val.data;
      this.getEditorData();
    },
    // 试做题组
    handleTestQuestionGroup() {
      this.showBrush = true
      // ${location_QuestionBank(window)} localhost:3000
      this.brushIframeRouter = `${location_QuestionBank(window)}/brush/${
        this.gitem.foreignID ? this.gitem.foreignID : "0"
      }`;
      // this.brushIframeRouter = `http://localhost:3000/qb/brush/${this.gitem.foreignID }`;
    },
    // 测试题组Dialog关闭
    handleTestTopicIframeClose() {
      this.showBrush = false
    },
    // 清空题组ID
    handleClearForeignID() {
      this.saveTestlet({gid: 0, title: "", groupType: ""})
    },
    // 文件上传数量改变
    handleChangeLimit() {
      this.setUploadData()
    },
    // 全选
    handleCheckAllChange(val) {
      this.ruleForm.checkList = val ? this.acceptType : [];
      this.isIndeterminate = false;
      this.setUploadData()
    },
    // 
    handleCheckedChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.acceptType.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.acceptType.length;
      this.setUploadData()
    },
    // 设置数据
    setUploadData() {
      this.gitem.limit = this.ruleForm.limit
      this.gitem.accept = this.ruleForm.checkList.join(',')
      this.$parent.$parent.$parent.handelChange("guidelines");
      debugger
    },
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy();
    this.editor = null;
    // this.$parent?.$parent?.$parent?.handelChange("guidelines"); 销毁时不需要设置引导文的改变状态
  },
};
</script>

<style  lang="stylus">
$boderColor = solid 1px #b7b2b2;

.editTextBox {
  .el-dialog__wrapper {
    // pointer-events: none;
  }

  .inputName {
    margin-top: 10px;
  }

  .placeholder {
    top: 0;
  }
}

.editText {
  position: relative;
  border: solid 1px #cbcbcb;

  .open_closeEditIcon {
    z-index: 999;
    cursor: pointer;
    position: absolute;
    right: 10px;
    bottom: 10px;
    transform: rotate(180deg);

    img {
      width: 20px;
      height: 9px;
    }
  }

  .edit {
    margin: 0 auto;
    max-width: 550px;
    // border-bottom: solid 1px #cbcbcb;
    transition: all 0.1s linear;
  }

  .toolBar {
    width: 100%;
    display: flex;
    justify-content: space-between;
    height: 52px;
    border-bottom: solid 1px #cbcbcb;

    .richTextTool {
      flex: 1;
      line-height: 52px;
      text-align: center;

      .w-e-toolbar {
        flex-wrap: wrap;
        align-items: center;
        // max-width: 899px;
        height: 50.99px;

        // overflow-y: scroll;

        // overflow-x: hidden;
        .w-e-menu {
          width: 30px;
          height: 25px;
        }

        .w-e-menu-tooltip-up {
          top: -35px;
          line-height: 30px;
        }
      }

      .w-e-toolbar::-webkit-scrollbar {
        width: 0px;
      }
    }

    .otherTool {
      width: auto;
      // width: 368px;
      display: flex;

      .weightBox {
        width: 100px;
        height: 50.99px;

        .el-button {
          width: auto;
          float: right;
          height: 100%;
          width: 100%;
          border-radius: 0;
            border-top: 0;
            border-bottom: 0;
        }

        .el-input {
          width: auto;
          float: right;
          height: 100%;
          width: 100%;

          .el-input__inner {
            padding: 0 5px;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.79);
            // box-shadow: 0px 8px 16px 0px rgba(149, 126, 126, 0.15);
            border-radius: 0;
            font-family: PMingLiU-ExtB;
            font-size: 20px;
            color: rgba(19, 18, 18, 0.89);
            opacity: 0.99;
            border: 0;
            border-left: solid 1px #cbcbcb;
            border-right: solid 1px #cbcbcb;
          }

          .el-input__inner::-ms-input-placeholder {
            font-size: 16px;
            text-align: center;
            // line-height: 120px;
          }

          .el-input__inner::-webkit-input-placeholder {
            font-size: 16px;
            text-align: center;
            // line-height: 100px;
          }
        }
      }

      .shortAnswer {
        cursor: pointer;
        position: relative;
        width: 162px;
        height: 51px;
        text-align: center;
        line-height: 51px;
        background-color: rgba(255, 255, 255, 0.79);
        // box-shadow: 0px 8px 16px 0px rgba(149, 126, 126, 0.15);
        border: 0;

        img {
          position: absolute;
          right: 12px;
          top: 50%;
          transform: translate(0, -50%);
        }

        .el-select {
          line-height: 1;

          .el-input {
            .el-input__inner {
              height: 51px;
              border: none;
              text-align: center;
              font-family: PMingLiU-ExtB;
              font-size: 20px;
              color: rgba(35, 34, 34, 0.88);
            }
          }
        }
      }

      .moveIcon {
        cursor: move;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 41px;
        height: 51px;
        // background-color: #ffffff;
        // box-shadow: 0px 8px 16px 0px rgba(149, 126, 126, 0.15);
        border-left: solid 1px #cbcbcb;

        i {
          font-size: 34px;
          color: #707070;
        }
      }

      .uMoveIcon {
        cursor: revert;
      }
    }
  }

  .uShowEdit {
    padding: 0 !important;
    min-height: 0 !important;
    height: 0 !important;
    border: none !important;

    .w-e-text-container {
      background: inherit;

      .w-e-text {
        height: 0;
        min-height: 0 !important;
      }
    }
  }
}

.eidt-blur {
}

.unOpen {
  cursor: pointer;
  border: none;
  height: 60px;
  // box-shadow: 3px 4px 10px 0px rgba(0, 0, 0, 0.16);
  border: $boderColor;
  border-radius: 10px;
  transition: all 0.2s linear;

  .typeIconBox {
    .uhoverIcon {
      display: block;
    }

    .hoverIcon {
      display: none;
    }
  }

  .unopenContent {
    padding: 0 20px 0 12px;
    display: flex;
    align-items: center;
    height: 100%;

    .weightInTaskBox {
      // max-width: 80%;
      display: flex;
      align-items: center;
      margin-left: 15px;
      flex: 1;
      font-family: PMingLiU-ExtB;
      font-size: 14px;
      color: rgba(19, 18, 18, 0.89);
      overflow: hidden;

      span, h1, h2, h3, h4, h5, p, div, b, li, font, strong {
        font-size: 14px !important;
      }

      span {
        display: inline-block;
        margin-right: 10px;
        max-height: 50px;

        .spanTitle {
          // display: inline-block;
          font-weight: bold;
        }

        p {
          display: flex;
          align-items: center;
          // max-height: 100%;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          min-width: 0;

          img {
            max-height: 50px;
            width: auto;
          }

          video {
            max-height: 50px;
            max-width: 90px;
          }

          video::-webkit-media-controls {
            display: none !important;
          }
        }
      }

      span:first-child {
        max-width: 60%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    .openIconbox {
      margin: 0 0 0 auto;

      img {
        cursor: pointer;
      }
    }
  }
}

.unOpen:hover {
  box-shadow: 3px 4px 10px 0px rgba(0, 0, 0, 0.16);
  border-color: #fee9c5;
  background: #fee9c5;

  .typeIconBox {
    .uhoverIcon {
      display: none;
    }

    .hoverIcon {
      display: block;
    }
  }
}

.brushTopicType {
  padding: 0 17px 0 9px;
  // margin-top: 13px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 50px;
  background-color: #fed48c;
  border: $boderColor;
  border-radius: 5px;
  opacity: 0.5;
  transition: all 0.2s linear;

  .btnListBox {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .btn {
      color: #2c3e50;
      margin-left: 10px;
      cursor: pointer;
    }
  }

  .startMustTips {
    top: 0 !important;
  }
}

.brushTopicType:hover {
  border-color: #fed48c;
  box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
}

.w-e-toolbar {
  z-index: 2 !important;

  .w-e-menu {
    .w-e-panel-container {
      margin-left: -20px;
    }
  }
}

.w-e-text-container {
  z-index: 1 !important;
  background: inherit;

  .placeholder {
    top: 0;
  }
}

.editTextHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.w-e-menu-tooltip {
  /* z-index: 100003 !important; */
}

.uploadFileInput {
  display: none;
}
</style>